namespace RBAC.Read.Api.Application.Handler.QualityHandler
{
    using MediatR;
    using Microsoft.Extensions.Logging;
    using RBAC.Domain.QualityManage;
    using RBAC.ErrorCode;
    using RBAC.Interstructrue.Base;
    using RBAC.Read.Api.Application.Command.QualityCommand;
    using RBAC.Read.Api.Application.Dto.Quality;
    using System.Linq;

    /// <summary>
    /// 质量工单分页查询处理器（无筛选条件）。
    /// </summary>
    /// <remarks>
    /// 主要逻辑：
    /// 1. 规范化分页参数（PageIndex、PageSize）。
    /// 2. 调用仓储分页接口 <c>GetPaged</c> 并按 <see cref="GetQualityOrderListCommand.OrderBy"/> 排序。
    /// 3. 将实体映射为 <see cref="QualityOrderListItemDto"/> 集合并返回。
    /// 4. 统一取消与异常处理。
    /// </remarks>
    /// </summary>
    public class GetQualityOrderListHandler : IRequestHandler<GetQualityOrderListCommand, APIPaging<QualityOrderListItemDto>>
    {
        private readonly IBaseRepository<QualityOrder> _orderRepo;
        private readonly ILogger<GetQualityOrderListHandler> _logger;

        public GetQualityOrderListHandler(IBaseRepository<QualityOrder> orderRepo, ILogger<GetQualityOrderListHandler> logger)
        {
            _orderRepo = orderRepo;
            _logger = logger;
        }

        /// <summary>
        /// 处理“质量工单分页查询”请求。
        /// </summary>
        /// <param name="request">分页命令。</param>
        /// <param name="cancellationToken">取消令牌。</param>
        /// <returns>返回 <see cref="APIPaging{T}"/> 包装的分页数据。</returns>
        public Task<APIPaging<QualityOrderListItemDto>> Handle(GetQualityOrderListCommand request, CancellationToken cancellationToken)
        {
            var result = new APIPaging<QualityOrderListItemDto>();
            try
            {
                // 检查是否被取消
                cancellationToken.ThrowIfCancellationRequested();
                // 规范化分页参数
                if (request.PageIndex <= 0) request.PageIndex = 1;
                if (request.PageSize <= 0) request.PageSize = 10;

                // 记录检索日志
                _logger.LogInformation("开始获取质量工单分页 PageIndex={PageIndex}, PageSize={PageSize}", request.PageIndex, request.PageSize);

                // 仓储：分页获取数据
                var (orders, total) = _orderRepo.GetPaged(request.PageIndex, request.PageSize, string.Empty, request.OrderBy, null);

                // 映射为列表 DTO
                var dtoList = orders.Select(o => new QualityOrderListItemDto
                {
                    Id = o.Id,
                    OrderNo = o.OrderNo,
                    Title = o.Title,
                    ProductId = o.ProductId,
                    ProductName = o.ProductName,
                    OwnerUserId = o.OwnerUserId,
                    OwnerUserName = o.OwnerUserName,
                    ProcessCount = o.ProcessCount,
                    ReportCount = o.ReportCount,
                    Status = o.Status,
                    Remark = o.Remark
                }).ToList();

                // 设置返回结果
                result.Code = APIEnums.Success;
                result.PageDatas = dtoList;
                result.TotalCount = total;
                result.Msg = "获取质量工单分页成功";
            }
            catch (OperationCanceledException)
            {
                // 捕获取消异常
                _logger.LogWarning("获取质量工单分页被取消");
                result.Code = APIEnums.Error;
                result.Msg = "请求已取消";
                result.PageDatas = new List<QualityOrderListItemDto>();
                result.TotalCount = 0;
            }
            catch (Exception ex)
            {
                // 统一异常处理与日志
                _logger.LogError(ex, "获取质量工单分页失败: {Message}", ex.Message);
                result.Code = APIEnums.Error;
                result.Msg = "获取质量工单分页失败";
                result.PageDatas = new List<QualityOrderListItemDto>();
                result.TotalCount = 0;
            }

            return Task.FromResult(result);
        }
    }
}
